﻿using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;

namespace Services.Initial.PublicProject.PublicMethods;

public static class Token
{
    public static string GenerateToken(string apiKey, long expSeconds)
    {
        string[] array = apiKey.Split('.');
        if (array.Length != 2)
        {
            throw new ArgumentException("Invalid API key format.");
        }

        string value = array[0];
        string s = array[1];
        byte[] array2 = Encoding.UTF8.GetBytes(s);
        if (array2.Length < 32)
        {
            Array.Resize(ref array2, 32);
        }

        SigningCredentials signingCredentials = new SigningCredentials(new SymmetricSecurityKey(array2), "HS256");
        JwtSecurityToken token = new JwtSecurityToken(payload: new JwtPayload
          {
            { "api_key", value },
            {
                "exp",
                DateTimeOffset.UtcNow.ToUnixTimeSeconds() + expSeconds
            },
            {
                "timestamp",
                DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            }
        }, header: new JwtHeader(signingCredentials) { { "sign_type", "SIGN" } });
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
